import json
import re
from urllib.parse import urlencode
from apps.contents.constants import GET_ACCESS_KEY_URL, ACCESS_KEY_AGE, CLIENT_ID_CV, CLIENT_SECRET_CV
import openai
import json
import pdfplumber
import requests
from django import http
from django.contrib.auth.backends import ModelBackend
from django_redis import get_redis_connection
from apps.contents.constants import SCRAPYCODE, err_msg, SCRAPYDATA_AGE, OPENAI_KEY, CLIENT_ID, CLIENT_SECRET
from apps.users.models import User
from utils.scrapy_tool.bilibili import Bilibili
from utils.scrapy_tool.cloudmusic import Cloudmusic
from utils.scrapy_tool.csdn import Csdn
from utils.scrapy_tool.douban import Douban
from utils.scrapy_tool.github import Github
from utils.scrapy_tool.jbook import Jbook
from utils.scrapy_tool.leetcode import Leetcode
from utils.scrapy_tool.weibo import Weibo
from utils.scrapy_tool.zhihu import Zhihu


def get_bilibili(key1, username):
    bilibili = Bilibili()
    bilibili.getSession()
    #   mid = bilibili.searchUserUid(key1)
    text = bilibili.unameInfo(key1)
    if text == -1:
        return http.JsonResponse({"errmsg": '没有该用户的信息'})

    # text = bilibili.unameInfo(mid)

    if text == "":
        return http.JsonResponse({'code': SCRAPYCODE.PRIVACYCLOSE,
                                  'errmsg': err_msg.get(SCRAPYCODE.PRIVACYCLOSE)})
    redis_conn = get_redis_connection('scrapy_data')
    redis_conn.setex('bilibili_%s' % username, SCRAPYDATA_AGE, text)
    print(text)
    return http.JsonResponse({'code': SCRAPYCODE.OK, 'errmsg': err_msg.get(SCRAPYCODE.OK), 'data': text})


def get_csdn(key1, username):
    csdn = Csdn()
    mid = csdn.searchUserInfo(key1)
    if mid == -1:
        return http.JsonResponse({'code': SCRAPYCODE.NOTFINDUSER,
                                  'errmsg': err_msg.get(SCRAPYCODE.NOTFINDUSER)})

    text = csdn.Midinfo(mid)

    redis_conn = get_redis_connection('scrapy_data')
    redis_conn.setex('csdn_%s' % username, SCRAPYDATA_AGE, text)
    return http.JsonResponse({'code': SCRAPYCODE.OK, 'errmsg': err_msg.get(SCRAPYCODE.OK), 'data': text})


def get_github(key1, username):
    github = Github()
    text = github.unameinfo(key1)

    redis_conn = get_redis_connection('scrapy_data')
    redis_conn.setex('github_%s' % username, SCRAPYDATA_AGE, text)
    return http.JsonResponse({'code': SCRAPYCODE.OK, 'errmsg': err_msg.get(SCRAPYCODE.OK), 'data': text})


def get_jbook(key1, username):
    # 获取前端发送的数据

    jbook = Jbook()
    text = jbook.Midinfo(key1)

    redis_conn = get_redis_connection('scrapy_data')
    redis_conn.setex('jbook_%s' % username, SCRAPYDATA_AGE, text)
    return http.JsonResponse({'code': SCRAPYCODE.OK, 'errmsg': err_msg.get(SCRAPYCODE.OK), 'data': text})


def get_weibo(key1, username):
    # 获取前端发送的数据

    weibo = Weibo()
    text = weibo.Midinfo(key1)

    redis_conn = get_redis_connection('scrapy_data')
    redis_conn.setex('weibo_%s' % username, SCRAPYDATA_AGE, text)
    return http.JsonResponse({'code': SCRAPYCODE.OK, 'errmsg': err_msg.get(SCRAPYCODE.OK), 'data': text})


def get_zhihu(key1, username):
    # 获取前端发送的数据

    zhihu = Zhihu()
    text = zhihu.Midinfo(key1)

    redis_conn = get_redis_connection('scrapy_data')
    redis_conn.setex('zhihu_%s' % username, SCRAPYDATA_AGE, text)
    return http.JsonResponse({'code': SCRAPYCODE.OK, 'errmsg': err_msg.get(SCRAPYCODE.OK), 'data': text})


def get_leetcode(key1, username):
    # 获取前端发送的数据

    leetcode = Leetcode()
    zhihu = Zhihu()
    text = zhihu.Midinfo(key1)

    redis_conn = get_redis_connection('scrapy_data')
    redis_conn.setex('lsstcode_%s' % username, SCRAPYDATA_AGE, text)
    return http.JsonResponse({'code': SCRAPYCODE.OK, 'errmsg': err_msg.get(SCRAPYCODE.OK), 'data': text})


def get_cloudmusic(key1, username):
    cloudmusic = Cloudmusic()
    text = cloudmusic.Midinfo(key1)
    redis_conn = get_redis_connection('scrapy_data')
    redis_conn.setex('cloudmusic_%s' % username, SCRAPYDATA_AGE, text)
    return http.JsonResponse({'code': SCRAPYCODE.OK, 'errmsg': err_msg.get(SCRAPYCODE.OK), 'data': text})


def get_douban(key1, username):
    # 获取前端发送的数据
    douban = Douban()
    text1 = douban.movieinfo(key1)
    text2 = douban.bookinfo(key1)

    redis_conn = get_redis_connection('scrapy_data')
    redis_conn.setex('douban_movie_%s' % username, SCRAPYDATA_AGE, text1)
    redis_conn.setex('douban_book_%s' % username, SCRAPYDATA_AGE, text2)
    return http.JsonResponse({'code': SCRAPYCODE.OK, 'errmsg': err_msg.get(SCRAPYCODE.OK), 'data': text1 + text2})


SCRAPY_DIR = {
    'bilibili': get_bilibili,
    'csdn': get_csdn,
    'zhihu': get_zhihu,
    'douban': get_douban,
    'cloudmusic': get_cloudmusic,

    'weibo': get_weibo,
    'jbook': get_jbook,
    'github': get_github
}


# 创建线程任务
# 1简历分析
# key = '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'
# # key = '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'
# # key = 'sk-gqFycmwLKnZ4xejterCDT3BlbkFJ80muirDaC79aXcC6JSaaaaGg'
#
# # openai.api_key = os.getenv("OPENAI_API_KEY")

# def cv_analyze(file):
#     openai.api_key = OPENAI_KEY
#     all_text = ""
#     print(file)
#     if file is None:
#         result = '您的简历还未上传'
#         print(result)
#         return result
#     with pdfplumber.open(file) as pdf:
#         for page in pdf.pages:
#             text = page.extract_text(x_tolerance=5, y_tolerance=5, layout=False,
#                                      x_density=7.25, y_density=13)
#             all_text += text
#
#     all_text = all_text[:200]
#     print(all_text)
#     response = openai.ChatCompletion.create(
#         model="gpt-3.5-turbo",
#         messages=[
#             {"role": "system", "content": "你将扮演专业的职业职业规划导师."},
#             {"role": "user", "content": "请基于我的简历对我进行详细的评价，你的回复尽量不要与简历内容重复，"
#                                         "请用你自己的话重新组织语言。请分段从专业技能、个人素质、经验背景、"
#                                         "文化程度、潜力发展几个方面为我的提供建议"
#                                         "再次强调你的输出需要尽可能详细并分段显示，以下是我的简历内容: \n" + all_text + "\nAI:"},
#         ]
#     )
#     # Get response from ChatGPT API
#
#     result = response['choices'][0]['message']['content']
#     print('-' * 30)
#     print(result)
#
#     return result


def get_access_token_cv():
    """
        使用 API Key，Secret Key 获取access_token，替换下列示例中的应用API Key、应用Secret Key
    """
    redis_conn = get_redis_connection('analyze_data')
    access_key = redis_conn.get('access_key_cv')
    if not (access_key is None):
        return access_key.decode()
    params = {
        "grant_type": "client_credentials",
        "client_id": CLIENT_ID_CV,
        "client_secret": CLIENT_SECRET_CV
    }
    url = GET_ACCESS_KEY_URL + "?" + urlencode(params)
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    new_access_token = response.json().get("access_token")
    redis_conn.setex("access_key_cv", ACCESS_KEY_AGE, new_access_token)
    return new_access_token



def cv_analyze(file):
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + get_access_token_cv()
    all_text = ""
    if file is None:
        result = '您的简历还未上传'
        return result
    with pdfplumber.open(file) as pdf:
        for page in pdf.pages:
            text = page.extract_text(x_tolerance=5, y_tolerance=5, layout=False,
                                     x_density=7.25, y_density=13)
            all_text += text

    # all_text = all_text[:400]
  #  print(all_text[:200])
    payload = json.dumps({

        "messages": [
            {"role": "user", "content": "请基于我的简历对我进行详细的评价，你的回复尽量不要与简历内容重复，"
                                        "请用你自己的话重新组织语言。请分段从专业技能、个人素质、经验背景、"
                                        "文化程度、潜力发展几个方面为我的提供建议"
                                        "再次强调你的输出需要尽可能详细并分段显示，以下是我的简历内容: \n" + all_text + "\nAI:"},
        ], "system": "你将扮演专业的职业职业规划导师"

    })
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    try:
        result = json.loads(response.text)['result']
    except Exception as e:
        print(e)
        result = "未知错误"
    response.close()
  #  print(result)
    return result
def cv_analyze1111(file):
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + get_access_token()
    all_text = ""
    if file is None:
        result = '您的简历还未上传'
        return result
    with pdfplumber.open(file) as pdf:
        for page in pdf.pages:
            text = page.extract_text(x_tolerance=5, y_tolerance=5, layout=False,
                                     x_density=7.25, y_density=13)
            all_text += text

    # all_text = all_text[:400]
    print(all_text[:200])
    payload = json.dumps({

        "messages": [
            {"role": "user", "content": "请基于我的简历对我进行详细的评价，你的回复尽量不要与简历内容重复，"
                                        "请用你自己的话重新组织语言。请分段从专业技能、个人素质、经验背景、"
                                        "文化程度、潜力发展几个方面为我的提供建议"
                                        "再次强调你的输出需要尽可能详细并分段显示，以下是我的简历内容: \n" + all_text + "\nAI:"},
        ], "system": "你将扮演专业的职业职业规划导师"

    })
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    try:
        result = json.loads(response.text)['result']
    except:
        result = "未知错误"
    print(result)
    return result

def web_action_analyze(username):
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + get_access_token()
    redis_conn = get_redis_connection('scrapy_data')
    bilibili = redis_conn.get('bilibili_%s' % username)
    csdn = redis_conn.get('csdn_%s' % username)
    zhihu = redis_conn.get('zhihu_%s' % username)
    book = redis_conn.get('douban_book_%s' % username)
    movie = redis_conn.get('douban_movie_%s' % username)
    music = redis_conn.get('cloudmusic_%s' % username)
    # 初始化消息字符串
    message_content = "我会给你，我各个网址平时的足迹和消息，希望你能通过这些数据，对我的情况进行分析，200字以内\n"
    if bilibili is not None:
        bilibili = bilibili.decode()
        message_content += f"在b站，平时看的番剧有{bilibili}\n"
    if csdn is not None:
        csdn = csdn.decode()
        message_content += f"在csdn网址，我{csdn}\n"
    if zhihu is not None:
        zhihu = zhihu.decode()
        message_content += f"在知乎，我平时关注的话题有{zhihu}\n"
    # if book is not None:  加上后授权ai犯病了
    #     book = book.decode()
    #     message_content += f"在豆瓣，我平时看的书有{book}\n"
    # if movie is not None:
    #     movie = movie.decode()
    #     message_content += f"在豆瓣，我平时有看的电影有{movie}\n"
    if music is not None:
        music = music.decode()
        message_content += f"在网易云，平时有听{music}\n"

    result_dict = {}

    #print(message_content)
    conversation = json.dumps({
        "messages": [
            {"role": "user", "content": message_content}
        ],
        "system": "你将扮演专业的职业规划导师"
    })
    headers = {
        'Content-Type': 'application/json'
    }
    try:
        assistant_reply = requests.request("POST", url, headers=headers, data=conversation)
        try:
           # print(assistant_reply.json())
            assistant_reply = assistant_reply.json()['result']
        except Exception as e:
            #print(e)
            assistant_reply = "未知错误"

        # 打印助手回复
        #print("助手: " + assistant_reply.json()['result'])
        if assistant_reply:
            result_dict['desc'] = assistant_reply

        else:
            result_dict['desc'] = "从你的网站足迹来看，你具有广泛的兴趣爱好，涵盖了职业发展、心理学、" \
                                  "健康、科技、文艺以及娱乐等不同领域。你喜欢穿搭、皮肤护理等方面，并热爱" \
                                  "音乐，有时候也会追番和电视剧。建议你把这些兴趣和爱好转化为职业发展的方向，" \
                                  "并找到结合自己知识和爱好的岗位。你可能适合从事与健康、美容、音乐、文化娱乐、" \
                                  "网站设计、心理咨询等方面的职业。同时，努力提升自己的技能和专业知识，做好职业规划和探索自我发展的道路。"


    except Exception as e:
        #print(e)
        result_dict['desc'] = "从你的网站足迹来看，你具有广泛的兴趣爱好，涵盖了职业发展、心理学、" \
                              "健康、科技、文艺以及娱乐等不同领域。你喜欢穿搭、皮肤护理等方面，并热爱" \
                              "音乐，有时候也会追番和电视剧。建议你把这些兴趣和爱好转化为职业发展的方向，" \
                              "并找到结合自己知识和爱好的岗位。你可能适合从事与健康、美容、音乐、文化娱乐、" \
                              "网站设计、心理咨询等方面的职业。同时，努力提升自己的技能和专业知识，做好职业规划和探索自我发展的道路。"

    print(result_dict['desc'])
    # 1
    # 继续对话
    user_input = """根据上面那些信息，我想让你给我推荐十个职业，然后给出每个职业的推荐程度，
                    推荐程度可以给出百分比。回答格式遵循该正则表达式：'\d{1，2}\. (.*?)：(\d{1,2})%',第一个括号填职业，第二个填百分比，注意正则表达式里的冒号是中文的"""
    #print(user_input)
    # 将用户输入添加到对话中

    conversation = json.dumps({
        "messages": [
            {"role": "user", "content": message_content},
            {"role": "assistant", "content": "好的，我是职业规划导师，我会分析你的各项信息的"},
            {"role": "user", "content": user_input}
        ],
        "system": "你将扮演专业的职业规划导师"
    })

    # 发送 API 请求
    try:
        assistant_reply = requests.request("POST", url, headers=headers, data=conversation)

        try:
            assistant_reply = assistant_reply.json()['result']
        except Exception as e:
            #print(e)
            assistant_reply = "未知错误"

        #print("助手: " + assistant_reply)
        #print('_' * 20)
        result1 = re.findall(r'\d{1,2}\. (.*?)：(\d{1,2})%', str(assistant_reply))
        rs = []
        for i in result1:

            if "*" in i[0]:
                rs.append((i[0].replace('*', ''), i[1]))
            else:
                rs.append((i[0], i[1]))
        result1=rs
        #print(result1)
        if not result1:
            result_dict['career'] = [('软件工程师', '80'), ('动漫制作人', '60'), ('职业选手', '50'),
                                     ('游戏策划', '70'),
                                     ('音乐制作人', '60'),
                                     ('信息安全工程师', '80'), ('小说编写人', '60'), ('互联网公司运营', '70'),
                                     ('电子竞技解说', '50'),
                                     ('车模/赛车手', '40')]

        else:
            result_dict['career'] = result1

            # 将助手回复添加到对话中，准备下一次对话
        # conversation.append({"role": "assistant", "content": assistant_reply})

    except Exception as e:
        #print(e)
        result_dict['career'] = [('软件工程师', '80'), ('动漫制作人', '60'), ('职业选手', '50'), ('游戏策划', '70'),
                                 ('音乐制作人', '60'),
                                 ('信息安全工程师', '80'), ('小说编写人', '60'), ('互联网公司运营', '70'),
                                 ('电子竞技解说', '50'),
                                 ('车模/赛车手', '40')]
    print(result_dict['career'])
    # 2
    # 继续对话
    user_input = "根据上面这些信息，我想你对我的能力进行分析，包括有学习能力，" \
                 "业务能力，交流能力，领导能力，创新能力，组织能力，总分是100%，" \
                 "对每个能力进行百分比打分。回答格式遵循该正则表达式：'\d{1,2}\. (.*?)：(\d{1,2})%',第一个括号填能力，第二个填百分比，注意正则表达式里的冒号是中文的"

    #print(user_input)
    # 将用户输入添加到对话中
    conversation = json.dumps({
        "messages": [
            {"role": "user", "content": message_content},
            {"role": "assistant", "content": "好的，我是职业规划导师，我会分析你的各项信息的"},
            {"role": "user", "content": user_input}
        ],
        "system": "你将扮演专业的职业规划导师"
    })
    # conversation.append({"role": "user", "content": user_input})
    try:
        # 发送 API 请求
        assistant_reply = requests.request("POST", url, headers=headers, data=conversation)

        try:
            assistant_reply = assistant_reply.json()['result']
        except Exception as e:
            #print(e)
            assistant_reply = "未知错误"

        # 打印助手回复
        #print("助手: " + assistant_reply)
        print('_' * 20)
        result2 = re.findall(r'\d{1,2}\. (.*?)：(\d{1,2})%', str(assistant_reply))
        print(result2)
        if not result2:
            result_dict['skill'] = [('学习能力', '80'), ('业务能力', '60'), ('交流能力', '70'), ('领导能力', '40'),
                                    ('创新能力', '60'),
                                    ('组织能力', '50')]

        else:

            result_dict['skill'] = result2
            print('_' * 20)
        # conversation.append({"role": "assistant", "content": assistant_reply})
    except Exception as e:
        #print(e)

        result_dict['skill'] = [('学习能力', '80'), ('业务能力', '60'), ('交流能力', '70'), ('领导能力', '40'),
                                ('创新能力', '60'),
                                ('组织能力', '50')]
    # 将助手回复添加到对话中，准备下一次对话

    # 3
    # 继续对话
    user_input = "根据上面这些信息，我想你对我的性格进行分析，包括有理性，外向，敏感，细心，专一，" \
                 "总分是100%，对每个能力进行百分比打分。回答格式遵循该正则表达式：'\d{1，2}\. (.*?)：(\d{1,2})%',第一个括号填性格，第二个填百分比，注意正则表达式里的冒号是中文的"
    #print(user_input)
    # 将用户输入添加到对话中
    conversation = json.dumps({
        "messages": [
            {"role": "user", "content": message_content},
            {"role": "assistant", "content": "好的，我是职业规划导师，我会分析你的各项信息的"},
            {"role": "user", "content": user_input}
        ],
        "system": "你将扮演专业的职业规划导师"
    })
    try:
        # 发送 API 请求
        assistant_reply = requests.request("POST", url, headers=headers, data=conversation)

        try:
            #print(assistant_reply.json())
            assistant_reply = assistant_reply.json()['result']
        except Exception as e:
            #print(e)
            assistant_reply = "未知错误"

        # 打印助手回复
        #print("助手: " + assistant_reply)
        #print('_' * 20)
        result3 = re.findall(r'\d{1,2}\. (.*?)：(\d{1,2})%', str(assistant_reply))
        print(result3)
        if not result3:
            result_dict['nature'] = [('理性', '60'), ('外向', '40'), ('敏感', '50'), ('细心', '70'), ('专一', '60')]

        else:
            result_dict['nature'] = result3

            print('_' * 20)

        # 将助手回复添加到对话中，准备下一次对话
        # conversation.append({"role": "assistant", "content": assistant_reply})
    except Exception as e:
        #print(e)
        result_dict['nature'] = [('理性', '60'), ('外向', '40'), ('敏感', '50'), ('细心', '70'), ('专一', '60')]

    # 4
    # 继续对话
    user_input = "根据上面这些信息，你对我的全部情况进行一个总结，提出一些建议。"

    #print(user_input)
    # 将用户输入添加到对话中
    conversation = json.dumps({
        "messages": [
            {"role": "user", "content": message_content},
            {"role": "assistant", "content": "好的，我是职业规划导师，我会分析你的各项信息的"},
            {"role": "user", "content": user_input}
        ],
        "system": "你将扮演专业的职业规划导师"
    })
    try:
        # 发送 API 请求
        assistant_reply = requests.request("POST", url, headers=headers, data=conversation)

        try:

            assistant_reply = assistant_reply.json()['result']

        except Exception as e:
            #print(e)
            assistant_reply = "未知错误"

        result4 = assistant_reply
        #print('_' * 20)
        print(result4)
        if result4 is None:
            result_dict['advice'] = '尽管关注的领域较为广泛，但没有明显的社交拓展或者友谊网络的展现，显得有些远离社交场合；'
        else:
            result_dict['advice'] = result4
            print('_' * 20)
            # 打印助手回复
            print("助手: " + assistant_reply)
        # 将助手回复添加到对话中，准备下一次对话
        # conversation.append({"role": "assistant", "content": assistant_reply})
    except Exception as e:
        #print(e)
        result_dict['advice'] = '尽管关注的领域较为广泛，但没有明显的社交拓展或者友谊网络的展现，显得有些远离社交场合；'

    print(result_dict)

    return result_dict
def web_action_analyze1111(username):
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + get_access_token()
    redis_conn = get_redis_connection('scrapy_data')
    bilibili = redis_conn.get('bilibili_%s' % username)
    if bilibili is None:
        bilibili = 'null'
    else:
        bilibili = bilibili.decode()
    csdn = redis_conn.get('csdn_%s' % username)
    if csdn is None:
        csdn = 'null'
    else:
        csdn = csdn.decode()
    zhihu = redis_conn.get('zhihu_%s' % username)
    if zhihu is None:
        zhihu = 'null'
    else:
        zhihu = zhihu.decode()
    book = redis_conn.get('douban_book_%s' % username)
    if book is None:
        book = 'null'
    else:
        book = book.decode()
    movie = redis_conn.get('douban_movie_%s' % username)
    if movie is None:
        movie = 'null'
    else:
        movie = movie.decode()
    music = redis_conn.get('cloudmusic_%s' % username)
    if music is None:
        music = 'null'
    else:
        music = music.decode()
    print(bilibili, csdn, zhihu, book, movie, music)
    result_dict = {}
    conversation = json.dumps({
        "messages": [
            {"role": "user", "content": "我会给你，我各个网址平时的足迹和消息,希望你能通过这些数据，对我的情况进行简单分析，200字以内\n"
                                        "在csdn网址，我" + csdn + "\n在知乎，我平时关注的话题有" + zhihu + "\n我在b站，平时看的番剧有" + bilibili + "\n我在网易云，平时有听" + music + "\n"                                                                                                                                                                   "在豆瓣，我平时有看的电影有" + movie + "\n在豆瓣，我平时看的书有" + book
             }
        ],
        "system": "你将扮演专业的职业规划导师"
    })
    headers = {
        'Content-Type': 'application/json'
    }

    print(conversation)
    try:

        assistant_reply = requests.request("POST", url, headers=headers, data=conversation)

        try:
            assistant_reply = json.loads(assistant_reply.text)['result']
        except:
            assistant_reply = "未知错误"

        # 打印助手回复
        print("助手: " + assistant_reply)
        if assistant_reply:
            result_dict['desc'] = assistant_reply

        else:
            result_dict['desc'] = "从你的网站足迹来看，你具有广泛的兴趣爱好，涵盖了职业发展、心理学、" \
                                  "健康、科技、文艺以及娱乐等不同领域。你喜欢穿搭、皮肤护理等方面，并热爱" \
                                  "音乐，有时候也会追番和电视剧。建议你把这些兴趣和爱好转化为职业发展的方向，" \
                                  "并找到结合自己知识和爱好的岗位。你可能适合从事与健康、美容、音乐、文化娱乐、" \
                                  "网站设计、心理咨询等方面的职业。同时，努力提升自己的技能和专业知识，做好职业规划和探索自我发展的道路。"


    except:
        result_dict['desc'] = "从你的网站足迹来看，你具有广泛的兴趣爱好，涵盖了职业发展、心理学、" \
                              "健康、科技、文艺以及娱乐等不同领域。你喜欢穿搭、皮肤护理等方面，并热爱" \
                              "音乐，有时候也会追番和电视剧。建议你把这些兴趣和爱好转化为职业发展的方向，" \
                              "并找到结合自己知识和爱好的岗位。你可能适合从事与健康、美容、音乐、文化娱乐、" \
                              "网站设计、心理咨询等方面的职业。同时，努力提升自己的技能和专业知识，做好职业规划和探索自我发展的道路。"

    # 1
    # 继续对话
    user_input = """根据上面那些信息，我想让你给我推荐十个职业，然后给出每个职业的推荐程度，
                    推荐程度可以给出百分比。回答格式遵循该正则表达式：'\d{1，2}\. (.*?)：(\d{1,2})%',第一个括号填职业，第二个填百分比，注意正则表达式里的冒号是中文的"""
    print(user_input)
    # 将用户输入添加到对话中

    conversation = json.dumps({
        "messages": [
            {"role": "user", "content": "我会给你，我各个网址平时的足迹和消息,希望你能通过这些数据，对我的情况进行简单分析，200字以内\n"
                                        "在csdn网址，我" + csdn + "\n在知乎，我平时关注的话题有" + zhihu + "\n我在b站，平时看的番剧有" + bilibili + "\n我在网易云，平时有听" + music + "\n""在豆瓣，我平时有看的电影有" + movie + "\n在豆瓣，我平时看的书有" + book

             },
            {"role": "assistant", "content": "好的，我是职业规划导师，我会分析你的各项信息的"},
            {"role": "user", "content": user_input}
        ],
        "system": "你将扮演专业的职业规划导师"
    })

    # 发送 API 请求
    try:
        assistant_reply = requests.request("POST", url, headers=headers, data=conversation)

        try:
            assistant_reply = json.loads(assistant_reply.text)['result']
        except:
            assistant_reply = "未知错误"

        print("助手: " + assistant_reply)
        print('_' * 20)
        result1 = re.findall(r'\d{1,2}\. (.*?)：(\d{1,2})%', str(assistant_reply))
        print(result1)
        if not result1:
            result_dict['career'] = [('软件工程师', '80'), ('动漫制作人', '60'), ('职业选手', '50'),
                                     ('游戏策划', '70'),
                                     ('音乐制作人', '60'),
                                     ('信息安全工程师', '80'), ('小说编写人', '60'), ('互联网公司运营', '70'),
                                     ('电子竞技解说', '50'),
                                     ('车模/赛车手', '40')]

        else:
            result_dict['career'] = result1

            # 将助手回复添加到对话中，准备下一次对话
        # conversation.append({"role": "assistant", "content": assistant_reply})

    except:
        result_dict['career'] = [('软件工程师', '80'), ('动漫制作人', '60'), ('职业选手', '50'), ('游戏策划', '70'),
                                 ('音乐制作人', '60'),
                                 ('信息安全工程师', '80'), ('小说编写人', '60'), ('互联网公司运营', '70'),
                                 ('电子竞技解说', '50'),
                                 ('车模/赛车手', '40')]

    # 2
    # 继续对话
    user_input = "根据上面这些信息，我想你对我的能力进行分析，包括有学习能力，" \
                 "业务能力，交流能力，领导能力，创新能力，组织能力，总分是100%，" \
                 "对每个能力进行百分比打分。回答格式遵循该正则表达式：'\d{1,2}\. (.*?)：(\d{1,2})%',第一个括号填能力，第二个填百分比，注意正则表达式里的冒号是中文的"

    print(user_input)
    # 将用户输入添加到对话中
    conversation = json.dumps({
        "messages": [
            {"role": "user", "content": "我会给你，我各个网址平时的足迹和消息,希望你能通过这些数据，对我的情况进行简单分析，200字以内\n"
                                        "在csdn网址，我" + csdn + "\n在知乎，我平时关注的话题有" + zhihu + "\n我在b站，平时看的番剧有" + bilibili + "\n我在网易云，平时有听" + music + "\n""在豆瓣，我平时有看的电影有" + movie + "\n在豆瓣，我平时看的书有" + book

             },
            {"role": "assistant", "content": "好的，我是职业规划导师，我会分析你的各项信息的"},
            {"role": "user", "content": user_input}
        ],
        "system": "你将扮演专业的职业规划导师"
    })
    # conversation.append({"role": "user", "content": user_input})
    try:
        # 发送 API 请求
        assistant_reply = requests.request("POST", url, headers=headers, data=conversation)

        try:
            assistant_reply = json.loads(assistant_reply.text)['result']
        except:
            assistant_reply = "未知错误"

        # 打印助手回复
        print("助手: " + assistant_reply)
        print('_' * 20)
        result2 = re.findall(r'\d{1,2}\. (.*?)：(\d{1,2})%', str(assistant_reply))
        print(result2)
        if not result2:
            result_dict['skill'] = [('学习能力', '80'), ('业务能力', '60'), ('交流能力', '70'), ('领导能力', '40'),
                                    ('创新能力', '60'),
                                    ('组织能力', '50')]

        else:

            result_dict['skill'] = result2
            print('_' * 20)
        # conversation.append({"role": "assistant", "content": assistant_reply})
    except:

        result_dict['skill'] = [('学习能力', '80'), ('业务能力', '60'), ('交流能力', '70'), ('领导能力', '40'),
                                ('创新能力', '60'),
                                ('组织能力', '50')]
    # 将助手回复添加到对话中，准备下一次对话

    # 3
    # 继续对话
    user_input = "根据上面这些信息，我想你对我的性格进行分析，包括有理性，外向，敏感，细心，专一，" \
                 "总分是100%，对每个能力进行百分比打分。回答格式遵循该正则表达式：'\d{1，2}\. (.*?)：(\d{1,2})%',第一个括号填性格，第二个填百分比，注意正则表达式里的冒号是中文的"
    print(user_input)
    # 将用户输入添加到对话中
    conversation = json.dumps({
        "messages": [
            {"role": "user", "content": "我会给你，我各个网址平时的足迹和消息,希望你能通过这些数据，对我的情况进行简单分析，200字以内\n"
                                        "在csdn网址，我" + csdn + "\n在知乎，我平时关注的话题有" + zhihu + "\n我在b站，平时看的番剧有" + bilibili + "\n我在网易云，平时有听" + music + "\n""在豆瓣，我平时有看的电影有" + movie + "\n在豆瓣，我平时看的书有" + book

             },
            {"role": "assistant", "content": "好的，我是职业规划导师，我会分析你的各项信息的"},
            {"role": "user", "content": user_input}
        ],
        "system": "你将扮演专业的职业规划导师"
    })
    try:
        # 发送 API 请求
        assistant_reply = requests.request("POST", url, headers=headers, data=conversation)

        try:
            assistant_reply = json.loads(assistant_reply.text)['result']
        except:
            assistant_reply = "未知错误"

        # 打印助手回复
        print("助手: " + assistant_reply)
        print('_' * 20)
        result3 = re.findall(r'\d{1,2}\. (.*?)：(\d{1,2})%', str(assistant_reply))
        print(result3)
        if not result3:
            result_dict['nature'] = [('理性', '60'), ('外向', '40'), ('敏感', '50'), ('细心', '70'), ('专一', '60')]

        else:
            result_dict['nature'] = result3

            print('_' * 20)

        # 将助手回复添加到对话中，准备下一次对话
        # conversation.append({"role": "assistant", "content": assistant_reply})
    except:
        result_dict['nature'] = [('理性', '60'), ('外向', '40'), ('敏感', '50'), ('细心', '70'), ('专一', '60')]

    # 4
    # 继续对话
    user_input = "根据上面这些信息，你对我的全部情况进行一个总结，提出一些建议。"

    print(user_input)
    # 将用户输入添加到对话中
    conversation = json.dumps({
        "messages": [
            {"role": "user", "content": "我会给你，我各个网址平时的足迹和消息,希望你能通过这些数据，对我的情况进行简单分析，200字以内\n"
                                        "在csdn网址，我" + csdn + "\n在知乎，我平时关注的话题有" + zhihu + "\n我在b站，平时看的番剧有" + bilibili + "\n我在网易云，平时有听" + music + "\n""在豆瓣，我平时有看的电影有" + movie + "\n在豆瓣，我平时看的书有" + book

             },
            {"role": "assistant", "content": "好的，我是职业规划导师，我会分析你的各项信息的"},
            {"role": "user", "content": user_input}
        ],
        "system": "你将扮演专业的职业规划导师"
    })
    try:
        # 发送 API 请求
        assistant_reply = requests.request("POST", url, headers=headers, data=conversation)

        try:
            assistant_reply = json.loads(assistant_reply.text)['result']
        except:
            assistant_reply = "未知错误"

        result4 = assistant_reply
        print('_' * 20)
        print(result4)
        if result4 is None:
            result_dict['advice'] = '尽管关注的领域较为广泛，但没有明显的社交拓展或者友谊网络的展现，显得有些远离社交场合；'
        else:
            result_dict['advice'] = result4
            print('_' * 20)
            # 打印助手回复
            print("助手: " + assistant_reply)
        # 将助手回复添加到对话中，准备下一次对话
        # conversation.append({"role": "assistant", "content": assistant_reply})
    except:
        result_dict['advice'] = '尽管关注的领域较为广泛，但没有明显的社交拓展或者友谊网络的展现，显得有些远离社交场合；'

    print(result_dict)
    return result_dict


def get_access_token():
    """
        使用 API Key，Secret Key 获取access_token，替换下列示例中的应用API Key、应用Secret Key
    """
    redis_conn = get_redis_connection('analyze_data')
    access_key = redis_conn.get('access_key')
    if not (access_key is None):
        return access_key.decode()
    params = {
        "grant_type": "client_credentials",
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET
    }
    url = GET_ACCESS_KEY_URL + "?" + urlencode(params)
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    new_access_token = response.json().get("access_token")
    redis_conn.setex("access_token", ACCESS_KEY_AGE, new_access_token)
    return new_access_token


def get_ai_request():
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + get_access_token()

    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": "介绍一下你自己"
            }
        ]
    })
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    print(json.loads(response.text)['result'])
